package com.smileus.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dongheng
 *
 */
@SuppressWarnings("unchecked")
public interface Parser {
	/**
	 * @param source
	 * @return
	 */
	Object prase(String source);

	static Map<Class, Parser> PARSER_MAP = new HashMap<Class, Parser>() {
		private static final long serialVersionUID = 1L;
		{
			put(Boolean.class, new Parser() {
				public Object prase(String source) {
					return Boolean.parseBoolean(source);
				}
			});
			put(Character.class, new Parser() {
				public Object prase(String source) {
					if (source == null || "null".equals(source) || "".equals(source)) {
						return null;
					}
					if (source.length() > 1) {
						throw new RuntimeException("无法将" + source + "转化为Character类型。");
					}

					return source.charAt(0);
				}
			});
			put(Byte.class, new Parser() {
				public Object prase(String source) {
					return Byte.parseByte(source);
				}
			});
			put(Short.class, new Parser() {
				public Object prase(String source) {
					return Short.parseShort(source);
				}
			});
			put(Integer.class, new Parser() {
				public Object prase(String source) {
					return Integer.parseInt(source);
				}
			});
			put(Long.class, new Parser() {
				public Object prase(String source) {
					return Long.parseLong(source);
				}
			});
			put(Float.class, new Parser() {
				public Object prase(String source) {
					return Float.parseFloat(source);
				}
			});
			put(java.util.Date.class, new Parser() {
				@SuppressWarnings("deprecation")
				public Object prase(String source) {
					return new java.util.Date(Date.parse(source));
				}
			});
			put(java.sql.Date.class, new Parser() {
				@SuppressWarnings("deprecation")
				public Object prase(String source) {
					return new java.sql.Date(Date.parse(source));
				}
			});
			put(String.class, new Parser() {
				public Object prase(String source) {
					return source;
				}
			});
			put(StringBuffer.class, new Parser() {
				public Object prase(String source) {
					return new StringBuffer(source);
				}
			});
			put(StringBuilder.class, new Parser() {
				public Object prase(String source) {
					return new StringBuilder(source);
				}
			});
			put(BigDecimal.class, new Parser() {
				public Object prase(String source) {
					return new BigDecimal(source);
				}
			});
			put(BigInteger.class, new Parser() {
				public Object prase(String source) {
					return new BigInteger(source);
				}
			});
			put(Class.class, new Parser() {
				public Object prase(String source) {
					Object result = null;
					try {
						result = Class.forName(source);
					} catch (ClassNotFoundException e) {
						throw new RuntimeException(e);
					}
					return result;
				}
			});
		}
	};
}
